package bl;
import java.math.BigInteger;
import java.security.InvalidParameterException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class Common {

	static SecureRandom sc = new SecureRandom();

	static public byte[] concat(byte[] a, byte[] b) {
		byte[] output = new byte[a.length + b.length];
		System.arraycopy(a, 0, output, 0, a.length);
		System.arraycopy(b, 0, output, a.length, b.length);
		return output;
	}

	static public BigInteger randBigInteger(BigInteger max, int bitLength) {
		BigInteger output;
		do {
			output = new BigInteger(bitLength, sc);
		} while (output.compareTo(max) >= 0);

		return output;
	}

	static public byte[] SHA256(byte[] input) {
		MessageDigest digest = null;
		try {
			digest = MessageDigest.getInstance("SHA-256");
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return digest.digest(input);
	}

	public static byte[] CreatePaddedBigIntegerBytes(BigInteger bi,
			int bytesLength) {
		byte[] bytes = bi.toByteArray();
		if (bytes.length == bytesLength) {
			return bytes;
		} else if (bytes.length > bytesLength) {
			throw new InvalidParameterException(
					"The BigInteger value is represneted in more than bytesLength bytes. The bytesLength parameter value is "
							+ bytesLength);
		} else // need to pad with zero bytes
		{
			return Common.concat(new byte[bytesLength - bytes.length], bytes);
		}
	}
}
